package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.GiftsProduct;
import net.starwifi.duobao.entity.GiftsProductLog;
import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.GiftsProductLogService;
import net.starwifi.duobao.service.GiftsProductService;
import net.starwifi.duobao.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 新年活动(领取流量包产品)
 * Created by ruoo on 16/1/26.
 */
@Controller("apiYearDiscountController")
@RequestMapping(value = "/yd")
public class YearDiscountController extends BaseController {

    @Autowired
    GiftsProductService giftsProductService;

    @Autowired
    GiftsProductLogService giftsProductLogService;

    @Autowired
    MemberService memberService;

    /**
     * 活动主页
     */
    @RequestMapping(value = "/2016", method = RequestMethod.GET)
    public  String yearDiscount(HttpServletRequest request) {
        return "wx/yd-2016";
    }


    /**
     * 礼包，优惠券领取
     */
    @ResponseBody
    @RequestMapping(value = "/yd-receive-{id}", method = RequestMethod.GET)
    public Message yearDiscount(@PathVariable Long id, String type,HttpServletRequest request) {
        Member member=memberService.getCurrent();
        if(type.equals("gifts")){//礼包
            GiftsProduct giftsProduct=giftsProductService.find(id);
            if(giftsProduct==null){
                return Message.error("对不起,该礼包不存在");
            }
            if(giftsProduct.getEndDate().before(new Date())){
                return Message.error("对不起,该礼包活动已经过期");
            }
            //获取用户领取记录
            Long count=giftsProductLogService.getQueryCount("o.giftsId=?1 and o.memberId=?2",new Object[]{id,member.getId()});
            if(count>0){
                return Message.error("您已经领取过该礼包");
            }
            //领取
            GiftsProductLog giftsProductLog=new GiftsProductLog(member.getId(),member.getMobile(),id,giftsProduct.getName(),giftsProduct.getShowLogo(),Boolean.FALSE);
            giftsProductLogService.save(giftsProductLog);
            return Message.error("领取成功,请关注微信公众号进行激活");
        }
        if(type.equals("coupon")){//优惠券

        }
        return Message.success("领取成功");
    }


}
